<?php

// +----------------------------------------------------------------------
// | 用户
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 微尘 <yicmf@qq.com>
// +----------------------------------------------------------------------

namespace app\controller\api\v3;

use app\event\file\QrCode;
use app\event\index\Share as ShareEvent;
use app\event\ucenter\Feedback as FeedbackEvent;
use app\model\im\Chat;
use app\event\ucenter\UserSign as UserSignEvent;
use app\event\ucenter\User as UserEvent;
use app\event\ucenter\AuthGroup as AuthGroupEvent;
use app\event\ucenter\UserAuth;
use app\model\ucenter\AuthGroup;
use app\model\ucenter\AuthGroupApply;
use app\model\ucenter\Label as LabelModel;
use app\model\ucenter\LabelGroup as LabelGroupModel;
use app\model\ucenter\UserOauth;
use app\model\ucenter\UserTask as UserTaskModel;
use app\pay\event\UserBalance as UserBalanceEvent;
use app\pay\event\UserBalanceCash as UserBalanceCashEvent;
use app\model\ucenter\User as UserModel;
use app\model\ucenter\UserOauth as UserOauthModel;
use think\Exception;
use think\exception\HttpException;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Config;
use wechat\mini_program\Code as CodeMini;
use app\model\ucenter\UserMoneyLog as UserMoneyLogModel;
use app\model\ucenter\UserAuthentication as UserAuthenticationModel;
use app\model\admin\FeedBack as FeedbackModel;

class User extends Common
{

    // 首页
    public function index()
    {

        if ($this->user) {

//            $user['payPwd']  = $user['payPwd']?1:0;
            $info['all_profit'] = UserMoneyLogModel::where('money', '>', 0)
                ->where('user_id', $this->user['id'])->sum('money');
//            $info['all_profit'] = UserMoneyLogModel::where('money', '>', 0)
//                ->where('user_id', $this->user['id'])
//                ->where('type', 'in', [11, 12, 13, 14, 15, 16, 18, 20, 21, 66])->sum('money');
//            $user['profit'] =sprintf('%.2f', $user['profit']);
//            //推荐人
//            $user['recommend'] = $user['pid']?Db::name('user')->where('id',$user['pid'])->value('nickname'):'无';
//            //实名
//            $real_name = Db::name('user_authentication')->where('uid',$this->auth->id)->find();
//            $user['real_name'] = $real_name?$real_name['name']:'';
//            $user['id_card'] = $real_name?$real_name['idNumber']:'';

            return $this->successAjax($info);
        } else {
            return $this->errorAjax('用户未登录');
        }

    }

    // 访客页面
    public function home()
    {

        if ($this->user) {
            $user = UserModel::with('avatar')->where('short_code', $this->request->param('short_code'))->find();
            $data['user'] = $user;
            $data['is_follow'] = $this->user->follows()->wherePivot('follow_id', $user['id'])->find() ? 1 : 0;
            $data['info']['fans'] = $user->fans()->wherePivot('status', 1)->count();
            $data['info']['history'] = 0;
            $data['info']['like'] = $user->fans()->wherePivot('status', 1)->count();;
            $data['info']['follow'] = $user->follows()->wherePivot('status', 1)->count();;
            $data['info']['post'] = $user->posts()->where('status', 1)->count();
            $data['info']['comment'] = $user->comments()->where('status', 1)->count();
            return $this->successAjax($data);
        } else {
            return $this->errorAjax('用户未登录');
        }

    }

    // 访客页面
    public function recommend()
    {
        if ($this->request->isPost()) {
            $code = $this->request->param('mobile');
            if (strpos(strtolower($code), 'f') !== false) {
                $code = str_replace('f', '', strtolower($code));
            }
            $invite = UserModel::where('mobile|shareCode', $code)->find();
            if ($invite) {
                if ($invite['id'] == $this->user['id']) {
                    return $this->errorAjax('不能设置自己为邀请人');
                } else {
                    $this->user['pid'] = $invite['id'];
                    $this->user['bid'] = $invite['id'];
                    $this->user['agent_id'] = $invite['agent_id'];
                    $this->user->save();
                    return $this->successAjax('更改成功');
                }

            } else {
                return $this->errorAjax('邀请码不存在');
            }
        } else {
            $data['desc'] = '这是您的上级推荐人，快和他联系吧，他会给你 详细的指导和培训';
            $data['qr_code'] = $this->request->domain() . '/upload/qr.jpg';
            if ($this->user['pid'] == 38 || empty($this->user['pid']) || $this->user['id'] == 16006) {

                if ((strtotime($this->user['create_time']) + 86400 * 3) > time()) {
                    $data['allow_change'] = 1;

                    $data['desc'] = '您暂时没有邀请人，系统默认分配，您可以在3天内自助选择邀请人。';
                } else {
                    $data['allow_change'] = 0;
                }

            } else {
                $data['allow_change'] = 0;
            }
            return $this->successAjax($data);
        }


    }

    public function feedback()
    {

        if ($this->request->isPost()) {

            $data = $this->request->param();

            $result = $this->validate($this->request->post(), 'app\validate\ucenter\Feedback');
            if (true !== $result) {
                $data['code'] = 20002;
                $data['message'] = $result;
            } else {
                $user_event = new FeedbackEvent();
                $data = $user_event->add($this->request->param(), $this->user);
            }

            return $this->autoAjax($data);
        } else {
            $info = [];
            $info['lists'][] = '功能异常：功故障或不可以';
            $info['lists'][] = '产品建议：用的不爽，我有建议';
            $info['lists'][] = '安全问题：密码、诈骗等';
            $info['lists'][] = '订单问题：支付失败、发货等';
            $info['lists'][] = '其他问题';
            $info['image'] = 1;
            return $this->successAjax($info);
        }

    }

    public function message()
    {
        if ($this->request->isPost()) {
            $msg = $this->user->messages()->where('id', $this->request->param('id'))->find();
            if ($msg) {
                $msg['is_read'] = 1;
                $msg->save();
                return $this->successAjax($msg->save());
            } else {
                return $this->errorAjax('消息不存在');
            }
        } else {
            $info = $this->user->messages()->order('create_time desc')->where('is_read', 0)->paginate();
            return $this->successAjax($info);
        }

    }

    public function notice()
    {
        if ($this->request->isPost()) {

            $action = $this->request->param('deal');

            if ($action == 'read') {
                $msg = $this->user->messages()->where('id', $this->request->param('id'))->find();
                if ($msg) {
                    $msg['is_read'] = 1;
                    $msg->save();
                    return $this->successAjax('成功1');
                } else {
                    return $this->errorAjax('消息不存在');
                }
            } elseif ($action == 'delete') {
                $info = $this->user->messages()->where('id', $this->request->param('id'))->find();
                return $this->successAjax($info->delete());
            } else {
                return $this->successAjax($action);
            }

        } else {
            $sheet_id = $this->request->param('sheet_id', 1);
            if ($sheet_id == 1) {
                $data['lists'] = $this->user->messages()->order('create_time desc')->paginate();
            } elseif ($sheet_id == 2) {
                $data['lists'] = $this->user->messages()->order('create_time desc')->paginate();
            } else {
                $data['lists'] = $this->user->messages()->order('create_time desc')->where('status', 2)->paginate();
            }
            $data['sheets'][] = [
                'name' => '公告',
                'num' => 0,
            ];
            $data['sheets'][] = [
                'name' => '站内信',
                'num' => $this->user->messages()->where('is_read', 0)->count(),
            ];
//            $data['sheets'][] = [
//                'name' => '项目通知',
//                'num' => 0,
//            ];
            return $this->successAjax($data);
        }

    }

    public function push()
    {

        if ($this->request->isPost()) {

            $this->user['is_push'] = $this->request->param('is_push');
            $this->user->save();
            return $this->successAjax('修改成功');
        } else {
            return $this->errorAjax('请求错误');
        }

    }

    public function levels()
    {
        if ($this->user) {
            if ($this->is_examine) {
                $info = Db::name('member_info')->where('id', '>', 4)->select();
            } else {
                $info = Db::name('member_info')->where('id', '<', 4)->where('type', '<', 4)->select();
            };
            $data['levels'] = $info;
            $data['info']['effective_user'] = UserModel::where('pid', $this->user['id'])->where('is_effective', 1)->count();
            $data['info']['effective_money'] = UserEvent::get_effective_money($this->user['id']);
            $data['info']['f2'] = Db::name('user')->where('pid', $this->user['id'])->where('level', 'in', '2,3')->count();;
            $data['info']['percentage'] = round($data['info']['effective_user'] * 100 / $info[1]['effective_user'], 3);
            //TODO::累计业绩
            $data['info']['percentage_deposit'] = round($data['info']['effective_money'] * 100 / ($info[1]['money'] * 10), 3);
            $data['modular'] = ['void' => 22];
            return $this->successAjax($data);
        } else {

            return $this->errorAjax('请先登录', 410003);
        }

    }

    public function vip()
    {
        $data = pay(time(), 0.01, 'vip');
        return $this->successAjax($data);
    }

    /**
     * 用户绑定手机
     * @return mixed|string
     */
    public function bindMobile()
    {
        if ($this->request->isPost()) {
            // 安全验证码
            // 图像验证码
//				$result = $this->validate($this->request->post(), 'app\validate\ucenter\User.login');
//				if (true !== $result) {
//					$data['code'] = 20002;
//					$data['message'] = $result;
//				} else {
            $user_event = new UserEvent();
            $data = $user_event->bindMobile($this->request->param(), $this->user);
//				}
        } else {
            $data['code'] = 1;
            $data['message'] = '请求错误';
        }

        return $this->autoAjax($data);
    }

    /**
     * 用户绑定微信
     * @return mixed|string
     */
    public function bind()
    {
        if ($this->request->isPost()) {
            // 安全验证码
            $user_event = new UserEvent();
            $data = $user_event->bindWechat($this->request->param(), $this->user);
        } else {
            $data['code'] = 1;
            $data['message'] = '请求错误';
        }

        return $this->autoAjax($data);
    }

    public function show()
    {
        $data['user'] = $this->user;
        $data['user']['idCard'] = secrecy_show($data['user']['idCard'], 3, 13);

        return $this->successAjax($data);
    }

    /**
     * 任务详情
     * @return \think\Response
     */
    public function task()
    {
        $data['task'] = UserTaskModel::where('id', $this->request->param('id'))->where('user_id', $this->user['id'])->find();
        $data['html'] = 'asdad';
        $data['url'] = '';
        $data['open_url'] = '';

        return $this->successAjax($data);
    }

    public function logoff()
    {
        if ($this->request->isPost()) {
            // 安全验证码
            // 图像验证码
//				$result = $this->validate($this->request->post(), 'app\validate\ucenter\User.login');
//				if (true !== $result) {
//					$data['code'] = 20002;
//					$data['message'] = $result;
//				} else {
            $user_event = new UserEvent();
            $data = $user_event->logoff($this->request->param(), $this->user);
//				}
        } else {
            $data['code'] = 1;
            $data['message'] = '请求错误';
        }

        return $this->autoAjax($data);
    }

    public function red()
    {

        if ($this->request->isPost()) {
            if ($this->user['create_time'] > time_format('2024-12-10 14:59:59')) {

                if (Cache::has('user_get_red' . $this->user['id'])) {
                    $data['money'] = 0;
                    $data['title'] = '打开失败';
                    $data['tips'] = '操作频繁';
                } else {
                    Cache::set('user_get_red' . $this->user['id'], 1, 3600);
                    $log = UserMoneyLogModel::where('user_id', $this->user['id'])->where('type', 89)->find();
                    if ($log) {
                        $data['money'] = $log['money'];
                        $data['title'] = '恭喜您获得';
                        $data['tips'] = '已存入余额，可直接提现';
                    } else {
                        /**
                         * 1.88-15%
                         * 3.88-30%
                         * 6.88-35%
                         * 8.88-15%
                         * 18.88-5%
                         */
                        $rand = rand(0, 99);
                        if ($rand < 15) {
                            $data['money'] = 1.88;
                        } elseif ($rand < 45) {
                            $data['money'] = 3.88;
                        } elseif ($rand < 80) {
                            $data['money'] = 6.88;
                        } elseif ($rand < 95) {
                            $data['money'] = 8.88;
                        } else {
                            $data['money'] = 18.88;
                        }

                        UserEvent::money($data['money'], $this->user['id'], '新人红包', 89, $this->user['id']);
                        $data['title'] = '恭喜您获得';
                        $data['tips'] = '已存入余额，可直接提现';
                    }


                    Cache::delete('user_get_red' . $this->user['id']);
                }


            } else {
                $data['money'] = 0;
                $data['title'] = '打开失败';
                $data['tips'] = '当前活动仅限新人领取';
            }
        } else {
            if ($this->user && strtotime($this->user['create_time']) > strtotime('2024-12-10 12:00:00')) {

                $log = UserMoneyLogModel::where('user_id', $this->user['id'])->where('type', 89)->find();
                if (!$log) {

                    $data['has_red'] = 1;
                    $data['show_red_model'] = 1;
                } else {

                    $data['has_red'] = 0;
                    $data['show_red_model'] = 0;
                }
            } else {
//                if ($this->user['id']==16006)
//                {
//                    $data['has_red'] = 1;
//                    $data['show_red_model'] = 1;
//                }else{
//
//                    $data['has_red'] = 0;
//                    $data['show_red_model'] = 0;
//                }
                $data['has_red'] = 0;
                $data['show_red_model'] = 0;
            }
        }


        return $this->successAjax($data);
    }

    /**
     * 实名认证.
     * @return mixed|string
     */
    public function realname()
    {
        if ($this->request->isPost()) {
            // 安全验证码
            $param = $this->request->only(explode(',', 'fort_image,back_image,name,idcard_no,card_b_id,card_a_id'));
            // 图像验证码
            $result = $this->validate($param, 'app\validate\ucenter\UserAuth');
            if (true !== $result) {
                $data['code'] = 20002;
                $data['message'] = $result;
            } else {

                if ($param['fort_image'] == '/static/sfzzheng.png' || $param['fort_image'] == '/static/sfzfan.png') {
                    $data['code'] = 20002;
                    $data['message'] = '请上传身份证照片';
                } else {

//                if (UserAuthenticationModel::whereRaw("idNumber=:card_no OR card_no=:card_no", ['idcard_no' => $param['idcard_no']])->where('status', 1)->find()) {

//                $card = UserAuthenticationModel::where('idNumber|idcard_no', $param['idcard_no'])->where('status', 1)->find();
                    $card = UserModel::where('idCard', $param['idcard_no'])
                        ->where('status', 1)
                        ->where('is_agency', 0)
                        ->find();

                    if ($card) {
                        $data['code'] = 20002;
                        $data['message'] = '当前身份证已经注册';
                    } else {
                        if ($this->user['realName'] == 1) {
                            $data['code'] = 20002;
                            $data['message'] = '当前用户已实名';
                        } else {
                            $param['user_id'] = $this->user['id'];
                            $param['uid'] = $this->user['id'];
                            $param['idNumber'] = $param['idcard_no'];
                            $param['status'] = 0;
                            $auth = UserAuthenticationModel::create($param);
                            if ($auth) {
                                $result = naidcard($auth['idcard_no'], $auth['name']);
                                if ($result['code'] == 0) {
                                    $data['code'] = 0;
                                    $data['message'] = $result['msg'];
//                                $this->error($result['msg'], $result['data']);
                                } else {
                                    $auth['status'] = 1;
                                    $auth->save();
                                    $this->user['idCard'] = $auth['idcard_no'];
                                    $this->user['idCardName'] = $auth['name'];
                                    $this->user['nickname'] = $auth['name'];
                                    $this->user['realName'] = 1;
                                    $this->user['birthday'] = get_idcard_birthday($auth['idcard_no']);
                                    $this->user->save();
                                    $data['code'] = 0;
                                    $data['message'] = '认证通过';
                                }

                            } else {
                                $data['code'] = 20002;
                                $data['message'] = '系统故障，稍候再试';
                            }
                        }
                    }
                }
            }


        } else {
            $data['code'] = 1;
            $data['message'] = '请求错误';
        }

        return $this->autoAjax($data);
    }

    /**
     * 未读消息
     * @return mixed|string
     */
    public function count()
    {
        $data['code'] = 0;
        $data['data']['count'] = 1;
        return $this->autoAjax($data);
    }

    /**
     * 用户状态
     * @return mixed|string
     */
    public function status()
    {
        $data['code'] = 0;
        UserModel::where('id', $this->user['id'])->update(['active_time' => time_format()]);
        $data['message'] = 'success';
        return $this->autoAjax($data);
    }

    // 弹出提示
    public function tips()
    {
        $tag = $this->request->param('tag', 'home');
        $data['tag'] = $tag;
        $data['text'] = '';
        $data['image'] = '';
        $data['zpop'] = '';
        // 文本弹窗
//        $data['text'] =  [
//            'id'=>'11',
//            'url'=>'https://blog.csdn.net/weixin_45416117/article/details/121862599',
//            'title'=>'测试标题',
//            'content'=>'内容11111',
//            'height'=>'',
//            'show'=>'no',
//            'btn_text'=>'去查看',
//            'open_url'=>'',
//        ];
        //单图弹窗
//        $data['zpop'] =  [
//            'id'=>'11',
//            'image'=>'https://blog.csdn.net/weixin_45416117/article/details/121862599',
//            'height'=>'',
//            'show'=>'no',
//            'url'=>'',
//            'open_url'=>'',
//        ];
//        // 图片弹窗
//        $data['image'] = [
//            'id'=>'121',
//            'url'=>'',
//            'image'=>'https://v3.yunfuye.com/uploads/image/202412/10/6757dfd52fbf2.jpg',
//            'height'=>'200',
//            'show'=>'always',
//            'btn_text'=>'去查看',
//            'open_url'=>'',
//        ];
        return $this->successAjax($data);
    }

    // 信息
    public function info()
    {
        if ($this->user) {
            $data['code'] = 0;
            $data['data'] = $this->user;
            $data['data']['idCard'] = secrecy_show($this->user['idCard'], 3, 13);
//            $event = new ShareEvent();
//            $event->poster($this->user);
        } else {
            throw new Exception('当前未登录');
            $data['code'] = 400;
            $data['message'] = '当前未登录';
        }

        return $this->autoAjax($data);
    }
    // 信息

    /**
     * 设置当前登录客户端
     * @return \think\Response
     */
    public function client()
    {
        if ($this->user) {
            $data['code'] = 0;
            $this->user['client_id'] = $this->request->param('client_id');
            $this->user->save();
            $data['data'] = $this->user;
        } else {
            $data['code'] = 400;
            $data['message'] = '当前未登录';
        }

        return $this->autoAjax($data);
    }

    /**
     * 用户自己的站点配置
     * @return \think\Response
     */
    public function config()
    {
//			if ($this->user) {
        $data['code'] = 0;
        $data['data']['site_title'] = 'dds';
//			} else {
//				$data['code'] = 1;
//				$data['message'] = '当前未登录';
//			}

        return $this->autoAjax($data);
    }

    // 信息
    public function label()
    {
//			if ($this->user) {
        $data['code'] = 0;
        $data['data'] = LabelGroupModel::with('labels')->where('status', 1)->select();
//				$data['data'] = LabelModel::where('status',1)->select();
//				$data['data']['site_title'] = 'dds';
//			} else {
//				$data['code'] = 1;
//				$data['message'] = '当前未登录';
//			}

        return $this->autoAjax($data);
    }

    // 聊天记录
    public function chat()
    {
//			if ($this->user) {
        $data['code'] = 0;
//				$data['data'] = UserModel::with('avatar')->where('id','>',0)->select();
        //$this->user->chats()->with(['to_user'])
        //            ->where('status', 1)
        //            ->where('is_open', 1)
        //            ->where('queue', 0)
        //            ->order('last_message_time DESC')
        //            ->select();
        $data['data'] = Chat::with(['to_user' => ['avatar']])
            ->where('user_id', $this->user['id'])
            ->where('status', 1)
            ->where('is_open', 1)
            ->where('queue', 0)
            ->order('last_message_time DESC')
            ->paginate();
//			} else {
//				$data['code'] = 1;
//				$data['message'] = '当前未登录';
//			}

        return $this->autoAjax($data);
    }

    // 信息
    public function lists()
    {
//			if ($this->user) {
        $data['code'] = 0;
        $data['data']['a'] = UserModel::with('avatar')->where('id', '>', 0)->limit(3)->select();
        $data['data']['b'] = UserModel::with('avatar')->where('id', '>', 0)->limit(3)->select();
        $data['data']['c'] = UserModel::with('avatar')->where('id', '>', 0)->limit(3)->select();
//				$data['data'] = Chat::with(['to_user'=>['avatar']])->where('id','>',0)->select();
//			} else {
//				$data['code'] = 1;
//				$data['message'] = '当前未登录';
//			}

        return $this->autoAjax($data);
    }


    public function oauth()
    {
        if ($this->request->isPost()) {

            $wechat = $this->user->oauths()->where('status', 1)->where('channel', 'qq')->find();

            if ($wechat) {
                $wechat['status'] = -2;
                $wechat->save();
                // 接触绑定
            } else {
                // 新增绑定
                // 注册
                $oauth = [];
                $oauth['avatar'] = $this->request->post('avatarUrl');
                $oauth['nickname'] = $this->request->post('nickName');
                $oauth['open_id'] = $this->request->post('openId');
                $oauth['sex'] = $this->request->post('gender');
                $oauth['avatar'] = $this->request->post('avatarUrl');
                $oauth['info'] = $this->request->post();
                $oauth['channel'] = 'wechat';
                $oauth['user_id'] = $this->user['id'];
                if ($this->request->post('unionId')) {
                    $oauth['unionid'] = $this->request->post('unionId');
                }
                $oauth = UserOauthModel::create($oauth);
                $data['data']['wechat'] = $oauth;
            }
            $data['code'] = 0;
            return $this->autoAjax($data);
        } else {
            $data['code'] = 0;
            $data['data']['wechat'] = $this->user->oauths()->where('status', 1)->where('channel', 'wechat')->find();
            $data['data']['qq'] = $this->user->oauths()->where('status', 1)->where('channel', 'qq')->find();
            return $this->autoAjax($data);
        }

    }

// 首页
    public function auth()
    {
        if ($this->request->isPost()) {
            $auth = new UserAuth();
            $validate = $this->validate($this->request->post(), 'app\validate\ucenter\UserAuth');
            if ($validate === true) {
                $data = $auth->add($this->request->post(), $this->user);
            } else {
                $data['code'] = 1;
                $data['message'] = $validate;
            }
        } else {
            $data['code'] = 0;
            $data['data']['store'] = $this->user;
//				$data['data']['type'] =  ['物业入驻','个人开店（无营业执照）', '个体户/公司/门店/品牌 入驻', '供应商入驻'];
//				$data['data']['role'] = ['常规门店模块 （小店、网店、商超）', '餐饮类门店', '品牌类传播','小区'];
            if ($this->request->has('id')) {
                $data['data']['auth'] = $this->user->auths()->with(['front', 'back', 'hand'])->where('id', $this->request->param('id'))->find();
            } else {
//					$data['data']['auth'] = \app\model\ucenter\UserAuth::with('front,back,hand,license')->where('user_id',$this->user['id'])->where('status', '>', -2)->find();
                $data['data']['auth'] = $this->user->auths()->with(['front', 'back', 'hand'])->where('status', '>', -2)->find();
            }
        }

        return $this->autoAjax($data);
    }

// 关注
    public function follow()
    {
        if ($this->request->isPost()) {
            $auth = new UserEvent();
            $data = $auth->follow($this->request->post(), $this->user);
            return $this->autoAjax($data);
        } else {
            return $this->errorAjax();
        }
    }

// 关注
    public function unfollow()
    {
        if ($this->request->isPost()) {
            $auth = new UserEvent();
            $data = $auth->unfollow($this->request->post(), $this->user);
            return $this->autoAjax($data);
        } else {
            return $this->errorAjax();

        }

    }

    public function avatar()
    {
        if ($this->request->isPost()) {
            UserModel::where('id', $this->user['id'])->update(['avatar' => $this->request->post('avatar')]);
            return $this->successAjax('操作成功');
        } else {
            return $this->errorAjax();

        }

    }

    /**
     * 第三方完善用户信息
     * @return \think\response\Json
     * @throws \Exception
     */
    public function perfect()
    {
        try {
            // 检验验证码
            if (Session::has('bind_sms')) {
                $sms = Session::pull('bind_sms');
                if ($sms['expires_time'] < $this->request->time()) {
                    throw new \Exception('短信验证码超时，请重新获取');
                }
                if ($sms['code'] != $this->request->post('sms_code')) {
                    throw new \Exception('短信验证码填写错误');
                }
            }
            // 如果修改昵称，则需要同步修改商品商家关联信息
            if ($this->user['nickname'] != $this->request->post('nickname')) {
                $this->user['nickname'] = $this->request->post('nickname');
                $this->user->goods()->update(['user_nickname' => $this->user['nickname']]);
            }
            $this->user['phone'] = $this->request->post('phone');
            $this->user['password'] = md5(md5($this->request->post('password')));
            if (!$this->user->save()) {
                throw new \Exception('信息保存异常');
            }
            $data['code'] = 0;
            $data['user'] = $this->user;
        } catch (\Exception $e) {
            $data['code'] = 1;
            $data['message'] = $e->getMessage();
        }
        return $this->autoAjax($data);
    }


    public function profile()
    {
        if ($this->request->isPut()) {

//				$check = $this->validate($this->request->post(), '\app\validate\ucenter\User.setting');
//				if ($check === true) {
//            $this->user['avatar_id'] = $this->request->post('avatar_id');
            $this->user['wechat'] = $this->request->post('wechat', null, 'strip_tags');
//            $this->user['sex'] = $this->request->post('sex');
//				$this->user['auth_name'] = $this->request->post('auth_name', null, 'strip_tags');
//				$this->user['email'] = $this->request->post('email', null, 'strip_tags');
//				$this->user['birthday'] = $this->request->post('birthday');
            if ($this->user->save()) {
                $data['code'] = 0;
                $data['data'] = $this->user;
                $data['message'] = '修改成功';
            } else {
                $data['code'] = 1;
                $data['message'] = '信息未更新';
            }
//				} else {
//					$data['code'] = 1;
//					$data['message'] = $check;
//				}
        } else {
            $data['code'] = 0;
            $data['message'] = 'success';
        }
        return $this->autoAjax($data);
    }

    // 粉丝列表
    public function fans()
    {
        $user = UserModel::where('short_code', $this->request->param('short_code'))->find();
        if ($user) {
            $lists = $user->fans()->with('avatar')->paginate();
            return $this->successAjax($lists);
        } else {
            return $this->errorAjax('用户不存在');
        }
    }

    // 关注
    public function follows()
    {
        $user = UserModel::where('short_code', $this->request->param('short_code'))->find();
        if ($user) {
            $lists = $user->follows()->with('avatar')->paginate();
            return $this->successAjax($lists);
        } else {
            return $this->errorAjax('用户不存在');
        }
    }

    // 关注
    public function likes()
    {
        $user = UserModel::where('short_code', $this->request->param('short_code'))->find();
        if ($user) {
            $lists = $user->attitudes()->with(['post' => ['user']])->paginate();
            return $this->successAjax($lists);
        } else {
            return $this->errorAjax('用户不存在');
        }
    }

    // 关注
    public function comments()
    {
        $user = UserModel::where('short_code', $this->request->param('short_code'))->find();
        if ($user) {
            $lists = $user->comments()->with(['post' => ['user'], 'user'])->paginate();
            return $this->successAjax($lists);
        } else {
            return $this->errorAjax('用户不存在');
        }
    }

    public function sign()
    {
        $event = new UserSignEvent();
        if ($this->request->isPost()) {
            //签到
            $data = $event->in($this->request->post(), $this->user);
        } else {
            $data = $event->status($this->user);
            $data['data']['share_get'] = Config::get('ucenter.share_point');
            $data['data']['left_share'] = Config::get('ucenter.share_times') - $this->user->points()
                    ->where('change_code', 'share')
                    ->whereTime('create_time', 'today')->count();
        }
        return $this->autoAjax($data);
    }

    /**
     * 我的订单
     */
    public function orders()
    {
        if (0 == $this->request->param('status')) {
            $map[] = ['status', '>', -2];
        } else if (1 == $this->request->param('status')) {
            $map[] = ['status', '=', 1];
        } else if (2 == $this->request->param('status')) {
            $map[] = ['status', '=', 2];
        } else if (3 == $this->request->param('status')) {
            $map[] = ['status', '=', 3];
        } else if (4 == $this->request->param('status')) {
            $map[] = ['evaluation_time', '=', null];
            $map[] = ['status', '=', 5];
        } else {
            $map = [];
        }
        $data = $this->user->orders()->with(['goods' => ['cover', 'sku'], 'store'])->where($map)->order('create_time DESC')->paginate(50);

        return $this->successAjax($data);
    }

    public function point()
    {
        $data['code'] = 0;
        $data['data'] = $this->user->points()->order('id DESC')->paginate(50);
        $data['user'] = $this->user;
        return $this->autoAjax($data);
    }


    /**
     * 充值
     */
    public function recharge()
    {
        if ($this->request->isPost()) {
            $rec = new UserBalanceEvent();
            $data = $rec->recharge($this->request->post(), $this->user);
        } else {
            $data['code'] = 1;
            $data['message'] = '请求错误';
        }
        return $this->autoAjax($data);
    }

    /**
     * 申请提现
     */
    public function cash()
    {
        if ($this->request->isPost()) {
            $rec = new UserBalanceCashEvent();
            $data = $rec->apply($this->request->post(), $this->user);
        } else {
            $data['code'] = 1;
            $data['message'] = '请求错误';
        }
        return $this->autoAjax($data);
    }


    /**
     * 邀请注册二维码
     */
    public function invite()
    {
        if ($this->request->isPost()) {
            $event = new UserEvent();
            return $this->autoAjax($event->bindInviteCode($this->request->param(), $this->user));
        } else {
            $url = $this->request->domain() . '/ucenter/register/store.html?code=' . code_encode($this->user['id']);
            $qrcode = $this->request->domain() . QrCode::build($url, 'user_' . $this->user['id'] . '.png', 'invite');
            $data['url'] = $url;
            $data['qrcode'] = $qrcode;
            $data['title'] = '邀请注册';
            $data['content'] = '注册描述';
            $data['invite_num'] = 1;
            $data['invite'] = $this->user['invite'];

            $data['share']['url'] = $url;
            $data['share']['title'] = '第6个人点击可获得神秘奖励，看看你的运气！';
            $data['share']['introduce'] = '用户每邀请1位均可获得1积分，点击「邀请免费得」保存二维码并发送给您的好友，好友识别二维码下载，通过手机账号注册APP，就是用户邀请成功，1积分即刻到账，每日无上限，多邀多得。';
            $data['share']['image'] = $this->request->domain() . '/static/common/images/logo.png';

            return $this->successAjax($data);
        }

    }

    // 密码修改
    public function password()
    {
        if ($this->request->isPost()) {

            $event = new UserEvent();
            $data = $event->updatePassword($this->request->post(), $this->user);
        } else {
            $data['code'] = 1;
            $data['message'] = '请求错误';
        }
        return $this->autoAjax($data);
    }

    // 用户组
    public function group()
    {
//			if ($this->request->isPost()) {
//
//				$event = new AuthGroupEvent();
//				$data = $event->groupApply($this->request->post(), $this->user);
//				return $this->autoAjax($data);
//			} else {
        $data['group'] = AuthGroup::where('id', '>', 1)->where('is_apply', 1)->where('status', 1)->select();
//				$data['apply_status'] = AuthGroupApply::where('user_id',$this->user['id'])->where('status','in',[1,2])->value('status');
        return $this->successAjax($data);
//			}
    }

    public function pay_password()
    {
        if ($this->request->isPost()) {

            $event = new UserEvent();
            return json($event->updatePayPassword($this->request->post(), $this->user));
        } else {
            $data['code'] = 1;
            $data['message'] = '请求错误';
        }
        return $this->autoAjax($data);
    }

    public function password_reset()
    {
        if ($this->request->isPost()) {
            $event = new UserEvent();
            return json($event->password_reset($this->request->post('', null, 'strip_tags'), $this->user));
        } else {
            return $this->fetch();
        }
    }

    public function email_reset()
    {
        if ($this->request->isPost()) {
            $event = new UserEvent();
            return json($event->email_reset($this->request->post('', null, 'strip_tags'), $this->user));
        } else {
            return $this->fetch();
        }
    }

    public function pay_password_reset()
    {
        if ($this->request->isPost()) {
            $event = new UserEvent();
            return json($event->password_reset($this->request->post('', null, 'strip_tags'), $this->user));
        } else {
            return $this->fetch();
        }
    }

    // 密码修改
    public function updatePwdBySmsCode()
    {
        if ($this->request->isPost()) {
            $data = UserEvent::changePwd($this->request->post('new_password'), $this->user);
        } else {
            $data['code'] = 1;
            $data['message'] = '请求错误';
        }
        return $this->autoAjax($data);
    }

    public function payPassword()
    {
        if (!$this->request->isPost()) {
            throw new HttpException(500, '非法请求');
        } else {
            if ($this->user['pay_password']) {
                // 验证旧密码
                if ($this->user['pay_password'] !== md5_salt($this->request->post('old_pay_password'))) {
                    throw new \Exception('旧支付密码验证失败');
                }
            }
            // TODO:密码强度验证
            // 设置密码
            $this->user['pay_password'] = $this->request->post('new_pay_password');
            $this->user->save();
            $data['code'] = 0;
            $data['data'] = $this->user;
            $data['message'] = '支付密码修改成功';
        }
        return $this->autoAjax($data);
    }

    // 隐私设置
    public function privacy()
    {
        if ($this->request->isPost()) {
            $this->user['privacy'] = json_decode($this->request->post('privacy'), true);
            if ($this->user->save()) {
                $data['code'] = 0;
                $data['user'] = $this->user;
                $data['message'] = '修改已保存';
            } else {
                $data['code'] = 1;
                $data['message'] = '信息未更新';
            }
        } else {
            $data['code'] = 1;
            $data['message'] = '请求错误';
        }
        return $this->autoAjax($data);
    }

    /**
     * 我的账单记录
     */
    public function balance()
    {
        if ($this->request->isPost()) {
            ;
        } else {
            $data['code'] = 0;
            $data['data'] = $this->user->balances()->order('id DESC')->paginate(50);
            $data['user'] = $this->user;
        }
        return $this->autoAjax($data);
    }


    /**
     * 小程序的邀请图片
     * @author  : 微尘 <yicmf@qq.com>
     * @datetime: 2019/1/19 12:41
     */
    public function lite()
    {
        $dir = pathinfo(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'lite' . DS .
            str_replace('/', DS, time_format($this->user->getData('create_time'), 'Y/m/d/h/i/')) . 'test.png', PATHINFO_DIRNAME);
        $save_name = '1_' . $this->user['id'] . '.png';
        if (!is_file($dir . DS . $save_name)) {
            $litercode = pathinfo(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'litecode' .
                DS . str_replace('/', DS, time_format($this->user->getData('create_time'), 'Y/m/d/')) . 'test.png', PATHINFO_DIRNAME);
            $filename = '1_' . $this->user['id'] . '.png';
            if (!file_exists($litercode)) {
                //检查是否有该文件夹，如果没有就创建，并给予最高权限
                mkdir($litercode, 0700, true);
            }
            if (!file_exists($dir)) {
                //检查是否有该文件夹，如果没有就创建，并给予最高权限
                mkdir($dir, 0700, true);
            }
            if (!is_file($litercode . DIRECTORY_SEPARATOR . $filename)) {
                $resource = fopen($litercode . DIRECTORY_SEPARATOR . $filename, 'a');
                $codeMini = new CodeMini();
                $param = [];
                $param['scene'] = createCode($this->user['id']);
                $param['width'] = 280;
                $result = $codeMini->unlimit($param);
                fwrite($resource, $result);
                fclose($resource);
                $image_avatar = \think\Image::open($litercode . DIRECTORY_SEPARATOR . $filename);
                $image_avatar->thumb(200, 200)->save($litercode . DIRECTORY_SEPARATOR . $filename);
            }
            $image = \think\Image::open(ROOT_PATH . 'public' . DS . 'static' . DS . 'common' . DS . 'images' . DS . 'mini_share.png');
            // 头像
            if ($this->user['avatar']) {
                $avatar_path = pathinfo(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'avatar' . DS . str_replace('/', DS, time_format($this->user->getData('update_time'), 'Y/m/d/h/i/')), PATHINFO_DIRNAME);
                if (!file_exists($avatar_path)) {
                    //检查是否有该文件夹，如果没有就创建，并给予最高权限
                    mkdir($avatar_path, 0700, true);
                }
                $avatar_resure = $avatar_path . DS . $save_name;
                if (strpos($this->user['avatar'], 'file.zlaoban.com') !== false || strpos($this->user['avatar'], 'file.zlaoban.com') !== false) {
                    $avatar_url = str_replace('-avatar', '-request', $this->user['avatar']);
                } else {
                    $avatar_url = $this->user['avatar'];
                }
                $this->downloadImage($avatar_url, $avatar_path . DS, $save_name);
                if (!(strpos($this->user['avatar'], 'file.zlaoban.com') !== false || strpos($this->user['avatar'], 'file.zlaoban.com') !== false)) {
                    $image_avatar = \think\Image::open($avatar_resure);
                    $image_avatar->thumb(100, 100)->save($avatar_resure);
                }
            } else {
                $avatar_resure = pathinfo(ROOT_PATH . 'public' . DS . 'static' . DS . 'common' . DS . 'images' . DS, PATHINFO_DIRNAME) . DS . 'images' . DS . 'default_user_portrait.gif';
            }
            $image->water($litercode . DIRECTORY_SEPARATOR . $filename, [222, 552])->water($avatar_resure, [120, 320]);
            if (mb_strlen($this->user['nickname'], 'utf-8') > 10) {
                $nickname = mb_substr($this->user['nickname'], 0, 10, 'utf-8') . '...';
            } else {
                $nickname = $this->user['nickname'];
            }
            $image->text($nickname, realpath(ROOT_PATH . DS . 'data' . DS . 'ttf' . DS) . DS . 'msyh.ttc', 22, '#DDEA00', [305, 319])
                ->save($dir . DS . $save_name);
        }
        $request['request_url'] = 'http://api.zlaoban.com/uploads/lite/' . time_format($this->user->getData('create_time'), 'Y/m/d/h/i/') . $save_name;
        $request['code'] = createCode($this->user['id']);
        $data['code'] = 0;
        $data['data'] = $request;
        return $this->autoAjax($data);
    }

//		/**
//		 * 邀请图片
//		 * @return \think\response\Json
//		 */
//		public function request()
//		{
//			$dir = pathinfo(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'request' . DS .
//				str_replace('/', DS, time_format($this->user->getData('update_time'), 'Y/m/d/h/i/')) . 'test.png', PATHINFO_DIRNAME);
//			$save_name = $this->user['id'] . '.png';
//			$url = 'https://api.zlaoban.com/index/Invite/register?code=' . createCode($this->user['id']);
//			//         if (!is_file($dir.DS.$save_name)) {
//			$qrcode = pathinfo(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'qrcode' .
//				DS . str_replace('/', DS, time_format($this->user->getData('create_time'), 'Y/m/d/')) . 'test.png', PATHINFO_DIRNAME);
//			if (!file_exists($dir)) {
//				//检查是否有该文件夹，如果没有就创建，并给予最高权限
//				mkdir($dir, 0700, true);
//			}
//			if (!file_exists($qrcode)) {
//				//检查是否有该文件夹，如果没有就创建，并给予最高权限
//				mkdir($qrcode, 0700, true);
//			}
//			import('lib.PHPQrcode.phpqrcode');
//			$errorCorrectionLevel = intval(1); //容错级别
//			$matrixPointSize = intval(5); //生成图片大小
//			//生成二维码图片
//			\QRcode::png($url, $qrcode . DS . $save_name, $errorCorrectionLevel, $matrixPointSize);
//			$image = \think\Image::open(ROOT_PATH . 'public' . DS . 'static' . DS . 'common' . DS . 'images' . DS . 'share.png');
//			//         // 给原图左上角添加水印并保存water_image.png
//			$image->save($dir . DS . $save_name);
//			// 头像
//			if ($this->user['avatar']) {
//				$avatar_path = pathinfo(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'avatar' . DS . str_replace('/', DS, time_format($this->user->getData('update_time'), 'Y/m/d/h/i/')), PATHINFO_DIRNAME);
//				if (!file_exists($avatar_path)) {
//					//检查是否有该文件夹，如果没有就创建，并给予最高权限
//					mkdir($avatar_path, 0700, true);
//				}
//				$avatar_resure = $avatar_path . DS . $save_name;
//				if (strpos($this->user['avatar'], 'file.zlaoban.com') !== false || strpos($this->user['avatar'], 'file.zlaoban.com') !== false) {
//					$avatar_url = str_replace('-avatar', '-request', $this->user['avatar']);
//				} else {
//					$avatar_url = $this->user['avatar'];
//				}
//				$this->downloadImage($avatar_url, $avatar_path . DS, $save_name);
//				if (!(strpos($this->user['avatar'], 'file.zlaoban.com') !== false || strpos($this->user['avatar'], 'file.zlaoban.com') !== false)) {
//					$image_avatar = \think\Image::open($avatar_resure);
//					$image_avatar->thumb(100, 100)->save($avatar_resure);
//				}
//			} else {
//				$avatar_resure = pathinfo(ROOT_PATH . 'public' . DS . 'static' . DS . 'common' . DS . 'images' . DS, PATHINFO_DIRNAME) . DS . 'images' . DS . 'default_user_portrait.gif';
//			}
//			$image->water($qrcode . DS . $save_name, [222, 552])->water($avatar_resure, [120, 320]);
//			if (mb_strlen($this->user['nickname'], 'utf-8') > 10) {
//				$nickname = mb_substr($this->user['nickname'], 0, 10, 'utf-8') . '...';
//			} else {
//				$nickname = $this->user['nickname'];
//			}
//			$image->text($nickname, realpath(ROOT_PATH . DS . 'data' . DS . 'ttf' . DS) . DS . 'msyh.ttc', 22, '#DDEA00', [305, 319])
//				->save($dir . DS . $save_name);
//			//         }
//			$request['request_url'] = $url;
//			$request['request_img'] = 'http://api.zlaoban.com/uploads/request/' . time_format($this->user->getData('update_time'), 'Y/m/d/h/i/') . $save_name;
//			$data['code'] = 0;
//			$data['data'] = $request;
//			return $this->autoAjax($data);
//		}

    public function downloadImage($url, $path, $save_name)
    {
        if (!is_dir($path)) {
            //第三个参数是“true”表示能创建多级目录，iconv防止中文目录乱码
            mkdir(iconv("UTF-8", "GBK", $path), 0777, true);
        }
        ob_start();
        readfile($url);
        $img = ob_get_contents();
        ob_end_clean();
        $fp2 = fopen($path . $save_name, "a");
        if (fwrite($fp2, $img) === false) {
            throw new \Exception('无法写入图片');
        }
        fclose($fp2);
        return $path . $save_name;
    }


}
